package cn.yyt.yytravel.base.security;


import cn.yyt.yytravel.user.mapper.UserMapper;
import cn.yyt.yytravel.user.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;


@Component
public class SelfUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 检查用户名是否为空，为空则抛出异常
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        // 根据用户名从数据库查询用户信息
        UserVO userVO = userMapper.selectByUsername(username);
        // 如果查询不到用户，抛出异常
        if (userVO == null) {
            throw new UsernameNotFoundException("没有该用户");
        }
        // 创建用户详情对象，并设置用户信息
        SelfUserDetails userInfo = new SelfUserDetails();
        userInfo.setUsername(userVO.getUsername());
        userInfo.setPassword(userVO.getPassword());
        userInfo.setUserId(userVO.getId());

        // 初始化用户权限集合
        Set<GrantedAuthority> authoritiesSet = new HashSet();
        // 创建一个示例权限对象   因为没有具体的权限组
        GrantedAuthority authority = new SimpleGrantedAuthority("example");

        // 添加权限到用户权限集合中
        authoritiesSet.add(authority);
        // 设置用户权限
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;
    }
}